// 全局变量
var today = new Date();
var todayTxt = today.format('yyyy-MM-dd');


var MY_WD_ACCOUNT_SUPERVISION = (function() {

    function getSearchParams(){

        var data = {};

        // 日期 from - to
        var $dtFrom = $('#dtFrom');
        if ( !$dtFrom.val().length ){
            WeKnow.errorMsg('请输入查询开始日期');
            $dtFrom.focus();
            return false;
        }

        var dtFrom = $dtFrom.val();
        if ( !MY_VALIDATOR.isDate(dtFrom,'yyyy-MM-dd')){
            WeKnow.errorMsg('查询开始日期格式不正确');
            $dtFrom.focus();
            return false;
        }
        data.dtFrom = dtFrom;

        // 查询日期to
        var $dtTo = $('#dtTo');
        if ( !$dtTo.val().length ){
            WeKnow.errorMsg('请输入查询结束日期');
            $dtTo.focus();
            return false;
        }

        var dtTo = $dtTo.val();
        if ( !MY_VALIDATOR.isDate(dtTo,'yyyy-MM-dd')){
            WeKnow.errorMsg('查询结束日期格式不正确');
            $dtTo.focus();
            return false;
        }
        if($dtFrom.val()>$dtTo.val()){
            WeKnow.errorMsg('开始时间不能大于结束时间');
            return false;
        }
        data.dtTo = dtTo;

        //诊所名
        var searchName = $.trim( $('#searchName').val());
        if ( searchName.length ){
            data.name = searchName;
        }

        //医疗机构类型
        var institutionType = $("#institutionTypeSelect option:selected").val();
        data.institutionType = institutionType;

        //异常类别
        var status = $("#statusSelect option:selected").val();
        data.status = status;

        return data;
    }

    function illegalShow(data) {
        return data == 0 ? "正常" : ("<span style='color: red'>异常 (" + data + ")</span>");
    }

    /** 获取页面输入参数 */
    function getFromPar(){
        var data = {};

        // 标本日期 from - to
        var $dtFrom = $('#dtFrom');
        if ( !$dtFrom.val().length ){
            WeKnow.errorMsg('请输入查询开始日期');
            $dtFrom.focus();
            return false;
        }

        var dtFrom = $dtFrom.val();
        if ( !MY_VALIDATOR.isDate(dtFrom,'yyyy-MM-dd')){
            WeKnow.errorMsg('查询开始日期格式不正确');
            $dtFrom.focus();
            return false;
        }
        data.dtFrom = dtFrom;

        // 查询日期to
        var $dtTo = $('#dtTo');
        if ( !$dtTo.val().length ){
            WeKnow.errorMsg('请输入查询结束日期');
            $dtTo.focus();
            return false;
        }

        var dtTo = $dtTo.val();
        if ( !MY_VALIDATOR.isDate(dtTo,'yyyy-MM-dd')){
            WeKnow.errorMsg('查询结束日期格式不正确');
            $dtTo.focus();
            return false;
        }
        data.dtTo = dtTo;

        if($dtFrom.val()>$dtTo.val()){
            WeKnow.errorMsg('开始时间不能大于结束时间');
            return false;
        }

        // 地区ID
        var townId =  $('#townId').val();
        if ( townId.length ){
            data.townId = townId;
        }
        var institutionTypeSelect =  $('#institutionTypeSelect').val();
        if ( institutionTypeSelect.length ){
            data.institutionTypeFirst = institutionTypeSelect;
        }

        return data;
    }

    /**
     * 根据type、查询对应的内容。并作显示控制
     */
    function loadOneTypeInfo(){

        var operateType = parseInt ( $('#operateType').val());
        var institutionId = $('#institutionId').val();

        switch(operateType) {
            case 1://处方
                // 页面初期数据查询
                var $thead= $('thead#thead-prescription');
                var $tbody= $('tbody#tbody-prescription');// 明细
                var params = MY_SM_PRESCRIPTION_VIOLATE.getParams();
                MY_PRESCRIPTION_VIOLATE_COM.loadDetailItem(params,$thead,$tbody);


                $('#prescription_sec').show();
                break;

            case 3://消毒
                // 默认选中器械消毒
                //$('select.business-sub-type').find("option[value='101']").prop("selected",true);
                // $('section#instrument_disinfect_sec').find('select[name="businessSubType"]').val(101);
                // $('#businessSubType').val(101);
                // 初始化器械列表
                MY_SM_INSTRUMENT_DISINFECT.loadInstrumentList();

                var $tHead  = $('#tHeadDisinfectDetailList');
                var $tbody = $('#tbodyDisinfectDetailList');
                var params = MY_SM_INSTRUMENT_DISINFECT.getDetailParams();
                MY_INSTRUMENT_DISINFECT_COMMON.loadDetailItem(params, $tHead, $tbody);
                $('#instrument_disinfect_sec').show();
                break;
            case 4:

                // 初始来源列表
                MY_SM_WASTE_DELIVERY.loadInstrumentList();

                var $tHead  = $('#waste_thead');
                var $tbody = $('#waste_tbody');
                var params = MY_SM_WASTE_DELIVERY.getDetailParams();
                MY_WASTE_DELIVERY_COM.loadDetailItem(params,$tHead,$tbody);
                $('#waste_delivery_sec').show();
                break;
            case 5:

                var $thead = $('#test_report_thead');
                var $tbody = $('#test_report_tbody');

                var businessSubType = $('#test_sec').find('select[name="businessSubType"]').val();
                if ( businessSubType == 301 || businessSubType == 303  ){//医疗污水检测报告
                    var params = MY_SM_SEWAGE_TEST_REPORT.getParams();
                    MY_SEWAGE_TEST_REPORT_COM.loadItem(params,$thead,$tbody);
                } else  if ( businessSubType == 302 ){//污水余氯日常检测
                    var params = MY_SM_SEWAGE.getDetailParams();
                    MY_SEWAGE_COM.loadDetailItem(params,$thead,$tbody);
                }
                $('#test_sec').show();
                break;
            case 6://异地执业
                var $thead= $('thead#thead-remote');
                var $tbody= $('tbody#tbody-remote');// 明细
                var params = MY_SM_REMOTE.getParams();
                MY_REMOTE_COM.loadDetailItem(params,$thead,$tbody);
                $('#remote_sec').show();
                break;
            case 7://三天无处方
                var $thead= $('thead#thead-threeDay');
                var $tbody= $('tbody#tbody-threeDay');// 明细
                var params = MY_SM_threeDay.getParams();
                MY_THREEDAY_COM.loadDetailItem(params,$thead,$tbody);
                $('#threeDay_sec').show();
                break;
            default:
                WeKnow.errorMsg("未能识别的状态！");
                break;
        }
    }

    // 各业务数据状态查询
    function getSummarize(){

        var institutionId = $('#institutionId').val();

        var params = getFromPar();
        if(params) {
            params.institutionId = institutionId;
            //params.dateYm = $('#year').val() + '' + $('#month').val();

            WeKnow.loading();

            $.ajax({
                type: "POST",
                url: "invs_summarize.do/load_one_sum",
                dataType: "json",
                data: params,
                async: true,//异步调用
                success: function (data) {

                    WeKnow.closeLoading();

                    if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

                    if (data.errcode == 0) {

                        var _a = data.resModel;
                        // 处方
                        if (_a.prescriptionCheckSt == 0) {
                            $('#prescription_dis').text('正常');
                            $('#prescription_dis').css('color', '');
                        } else {
                            $('#prescription_dis').text('异常(' + _a.prescriptionIllegalCnt + ')');
                            $('#prescription_dis').css('color', 'red');
                        }
                        //异地执业
                        if (_a.remoteCheckSt == 0) {
                            $('#remote_dis').text('正常');
                            $('#remote_dis').css('color', '');
                        } else {
                            $('#remote_dis').text('异常(' + _a.remoteIllegalCnt+ ')');
                            $('#remote_dis').css('color', 'red');
                        }
                        //三天无处方
                        if (_a.threeDayCheckSt == 0) {
                            $('#threeDay_dis').text('正常');
                            $('#threeDay_dis').css('color', '');
                        } else {
                            $('#threeDay_dis').text('异常(' + _a.threeDayIllegalCnt+ ')');
                            $('#threeDay_dis').css('color', 'red');
                        }
                        //消毒
                        if (_a.disinfectCheckSt == 0) {
                            $('#instrument_disinfect_dis').text('正常');
                            $('#instrument_disinfect_dis').css('color', '');
                        } else {
                            $('#instrument_disinfect_dis').text('异常(' + _a.disinfectIllegalCnt + ')');
                            $('#instrument_disinfect_dis').css('color', 'red');
                            //设置默认
                            if(_a.disinfectIllegalCntA == 0 && _a.disinfectIllegalCntB > 0){
                                //101异常为0 则 默认为102
                                $('section#instrument_disinfect_sec').find('select[name="businessSubType"]').val(102);
                            }else{
                                $('section#instrument_disinfect_sec').find('select[name="businessSubType"]').val(101);
                            }
                        }
                        //医废
                        if (_a.wasteCheckSt == 0) {
                            $('#waste_delivery_dis').text('正常');
                            $('#waste_delivery_dis').css('color', '');
                        } else {
                            $('#waste_delivery_dis').text('异常(' + _a.wasteIllegalCnt + ')');//医废
                            $('#waste_delivery_dis').css('color', 'red');
                        }
                        //污水
                        if (_a.sewageCheckSt == 0) {
                            $('#sewage_dis').text('正常');
                            $('#sewage_dis').css('color', '');
                        } else {
                            $('#sewage_dis').text('异常(' + _a.sewageIllegalCnt + ')');
                            $('#sewage_dis').css('color', 'red');
                            //设置默认
                            if(_a.sewageIllegalCntA == 0 && _a.sewageIllegalCntB > 0){
                                //301异常为0 则 默认为302
                                $('#test_sec').find('select[name="businessSubType"]').val(302);
                            }else if(_a.sewageIllegalCntB == 0 && _a.sewageIllegalCntC > 0){
                                //302异常为0 则 默认为303
                                $('#test_sec').find('select[name="businessSubType"]').val(303);
                            }
                        }
                    } else if (data.errcode == -1) {
                        WeKnow.errorMsg(data.errMsg);
                    } else {
                        WeKnow.systemMsg('查询失败，请重新登录后再试');
                    }
                }
            });
        }
    }

    function initMain() {

        $(".my_date_control" ).datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'yy-mm-dd',//日期格式
            yearSuffix: '年', //年的后缀
            showMonthAfterYear:true,//是否把月放在年的后面
            maxDate: (function() {
                return todayTxt;
            })(),//最大日期
            yearRange: (function() {
                // '1990:2010'
                var year1 = '1900';
                var year2 = today.getFullYear();
                return year1 + ':' + year2;
            })(),
            monthNamesShort: ['01','02','03','04','05','06','07','08','09','10','11','12'],
            dayNamesMin: ['日','一','二','三','四','五','六'],
            onUpdatedDatepicker: function(_year, _month, _calendar) {
                var $c = $('div#ui-datepicker-div');
                $c.find('td[data-handler="selectDay"]').each(function(idx, d) {
                    var $d = $(d);
                    $d.css({'pointer-events': 'auto', 'opacity': 1});
                });
            }
        });

        //添加查看按钮
        var demo = document.getElementById("demo");
        demo.innerHTML += '<script type="text/html" id="barDemo">' +
            ' <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</' + 'a>' +
            '</' + 'script>';

        //查询按钮按下
        $('#search').on('click',function(){
            layui.use('table', function(){
                var table = layui.table;
                //执行一个laypage实例
                table.render({
                    elem: '#demo',
                    autoSort: false,
                    /*initSort: {
                        field: 'total', //排序字段，对应 cols 设定的各字段名
                        type: 'desc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
                    },*/
                    height: $(document).height() - $('#demo').offset().top - 22,
                    url: "invs_wd_account_supervision.do/load",
                    method: "POST",
                    where: getSearchParams(),
                    cellMinWidth: 80,
                    page: true,
                    limit: 10,
                    limits: [10, 20, 50, 100],
                    cols: [[
                        {field:'name', title:'医疗机构', align:'left', width:'30%'},
                        {field:'institutionTypeFirst', title:'医疗机构类型', align:'left', width:'15%'},
                        {field:'type10', title:'消毒登记', align:'center',width:'15%', sort:true,
                            templet:function (d) {
                                return illegalShow(d.type10);
                            }
                        },
                        {field:'type20', title:'医废登记', align:'center',width:'15%', sort:true,
                            templet:function (d) {
                                return illegalShow(d.type20);
                            }
                        },
                        {field:'type30', title:'检测审查', align:'center',width:'15%', sort:true,
                            templet:function (d) {
                                return illegalShow(d.type30);
                            }
                        },
                        {field:'operator', title:'操作', align:'center', width:'10%', toolbar: '#barDemo'},
                    ]],
                });

                table.on('sort(test)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                    //尽管我们的 table 自带排序功能，但并没有请求服务端。
                    //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
                    table.reload('demo', {
                        initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
                        ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                            field: obj.field //排序字段
                            ,order: obj.type //排序方式
                        }
                    });
                });

                //监听行工具事件
                table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                    var data = obj.data //获得当前行数据
                        ,layEvent = obj.event; //获得 lay-event 对应的值
                    if(layEvent === 'detail'){
                        $('#institutionId').val(data.pid);
                        $('#institution_name_dis').text(data.name);
                        $('#year_month').text('（' + $('#dtFrom').val() + ' 至 ' + $('#dtTo').val() + '）');
                        $('.toggle-input').toggle();
                        // 第一个tab显示
                        $('.div_tab_panel :visible:first').click();
                    }
                });
            });
        });

        $('#institutionTypeSelect').on('change',function(){
            $("button#search").trigger("click");
        });

        $('#statusSelect').on('change',function(){
            $("button#search").trigger("click");
        });

        $("button#search").trigger("click");
    }

    return {
        initMain:initMain,
        loadOneTypeInfo:loadOneTypeInfo,
        getSummarize:getSummarize,
    }
})();

var map = undefined;
var marker = undefined;
$(document).ready(function() {

    MY_WD_ACCOUNT_SUPERVISION.initMain();

    $('#backToWorkspace').on('click',function(){
        $('.toggle-input').toggle();
    });

    // panel切换
    $('.div_tab_panel').on('click',function(){
        var $that = $(this);
        // 记住点了哪个TAB
        $('#operateType').val($that.data('operate_idx'));
        // 选中TAB变换成高亮样式
        $('.active_tab').removeClass('active_tab');
        $that.addClass('active_tab');
        // 已显示出来的明细section隐藏掉
        $('section.detail_area').hide();
        MY_WD_ACCOUNT_SUPERVISION.getSummarize();//刷新各TAB的总件数
        // 显示对应tab的内容
        MY_WD_ACCOUNT_SUPERVISION.loadOneTypeInfo();
    });

    $('select.business-sub-type').change(function () {
        // 查询器械或场所列表
        MY_SM_INSTRUMENT_DISINFECT.loadInstrumentList();
    });

    // Bmap初始化
    $("#container").empty();
    // alert($("#container").html());
    map = new BMap.Map("container");
    map.enableScrollWheelZoom();   //启用滚轮放大缩小，默认禁用
    map.enableContinuousZoom();
    map.addControl(new BMap.NavigationControl());
    map.addControl(new BMap.NavigationControl());
    map.addControl(new BMap.ScaleControl());
    map.addControl(new BMap.OverviewMapControl());
    map.addControl(new BMap.MapTypeControl());
});

// 显示地图
$('#tbody-remote').on('click','button[name="showLocation"]',function(){
    $(".modal").modal("hide");
    $("#showMapModal").modal("show");
    var loginPositionStr = $(this).attr("loginPosition");
    var local=loginPositionStr.split(',');

    var point = new BMap.Point(local[0], local[1]);
    marker = new BMap.Marker(point);        // 创建标注
    map.addOverlay(marker);

    map.centerAndZoom(point, 15);
    map.panBy(400,350);
});

$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).removeData('bs.modal');
    if (marker) {
        map.removeOverlay(marker);
        map.panBy(-400, -350);
    }
});
